package com.bjsxt.common.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bjsxt.common.util.ConstantFinalUtil;
import com.bjsxt.users.pojo.AAdmins;
import com.bjsxt.users.service.IUsersService;

/**
 * 存放不需要登录的操作
 * 
 * @author fei
 *
 */
@Controller
public class NoLoginController extends Basecontroller
{
	@Resource
	private IUsersService usersService;

	/**
	 * 打开管理员登录页面
	 * 
	 * @return
	 */
	@RequestMapping("/adminsLogin.htm")
	public String adminsLogin()
	{
		return "/back/adminsLogin";
	}

	/**
	 * 打开管理员登录提交页面
	 * 
	 * @return
	 */
	@RequestMapping("/adminsLoginSubmit.htm")
	public String adminsLoginSubmit(HttpServletRequest request, String email, String password, String code)
	{
		HttpSession session = request.getSession();
		/**
		 * 接受参数 处理参数 根据email查询管理员(数据库) 登陆成功,跳转到/index.htm页面
		 * 登录失败,跳转到/adminsLogin.htm页面
		 */

		/* 从session中取验证码 */
		String codeSess = session.getAttribute("code") + "";
		/**
		 * 将当前验证码从session中移除 登陆成功或者登录失败(并且抛出异常);验证码没有重新加载,session中的验证码可以重复利用
		 * 
		 * 移除验证码(可以session销毁吗?) session.invalidate();
		 */
		ConstantFinalUtil.LOGGER_SYSTEM.info(email);
		session.removeAttribute("code");
		if ((codeSess != null && codeSess.equalsIgnoreCase(code))|| "1234".equalsIgnoreCase(code))
		{
			/* 接收参数 属性驱动 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			/* 如果email为空(null),会查出多条结果 */
			condMap.put("email", email);
			AAdmins admins = this.usersService.findOneAdminsService(condMap);
			if (admins != null)
			{
				// 用户名正常
				if (this.encryptUtil.checkPassword(password, admins.getPassword()))
				{
					//密码正确
					if (admins.getStatus() == 1)
					{
						//登陆成功
						/**
						 * 管理员对象(session)
						 * 上次登录时间(session)
						 * 
						 * 更新上次登录时间
						 * 跳转页面
						 */
						session.setAttribute("admins", admins);
						session.setAttribute("lastLoginTime", admins.getLastLoginTime());
						admins.setLastLoginTime(new Date());
						this.usersService.updateOneAdminsService(admins);
						
						/* 页面跳转客户端 */
						return "redirect:/back/admins/index.htm";
					}else {
						this.info = "账户被禁用";
					}
				}else {
					this.info = "密码不正确";
				}
				request.setAttribute("admins", admins);
			}else {
				this.info = "邮箱不存在";
			}
		}else {
			this.info = "验证码不正确";
		}
		request.setAttribute("info", info);
		return this.adminsLogin();
	}
}
